package de.upb.messerschmidt.set;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.upb.messerschmidt.set.entity.Event;
import de.upb.messerschmidt.set.entity.Location;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * Gets an {@link Event}'s data via an HttpPost and persists it.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class RegisterEventServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings({ "unchecked", "deprecation" })
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String locationString = req.getParameter("location");
		String dateString = req.getParameter("date");
		String title = req.getParameter("title");
		String description = req.getParameter("description");

		if (locationString == null || dateString == null || title == null
				|| description == null) {
			resp.setStatus(400);
			resp.getWriter().println("Please fill in all fields");
		} else {
			Date date = null;
			Location location = null;

			PersistenceManager pm = PMF.get().getPersistenceManager();

			Query query = pm.newQuery(Location.class);
			query.setFilter("name == nameParam");
			query.declareParameters("String nameParam");
			query.setOrdering("name desc");

			List<Location> results = (List<Location>) query
					.execute(locationString);

			if (!results.isEmpty()) {
				location = results.get(0);
			}

			try {
				SimpleDateFormat sdfToDate = new SimpleDateFormat("dd.MM.yyyy");
				date = sdfToDate.parse(dateString);
				// Fix for the Date-Bug
				date.setHours(23);
				date.setMinutes(59);
			} catch (Exception e) {
				resp.setStatus(400);
				e.printStackTrace();
				resp.getWriter().println(
						"Please use a valid date format: (dd.mm.yyyy)");
			}

			if (date != null && location != null) {
				Event event = new Event(date, location.getName(), title,
						description);

				try {
					location.getEvents().add(event.getTitle());

					pm.makePersistent(event);
					pm.refresh(location);
					pm.flush();

					resp.setStatus(200);
					resp.getWriter().println("Event registered successfully");
				} catch (Exception e) {
					e.printStackTrace();
					resp.setStatus(400);
					resp.getWriter().println("Failed to register Event");
				} finally {
					pm.close();
				}
			}
		}
	}

}
